<script lang="ts" setup>
import { Message } from '@arco-design/web-vue'
import { ClassInfoApi } from '@/apis'
import type { TableInstanceColumns } from '@/components/ProTable/type'

defineOptions({
  name: 'ImportClassStudent',
})

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)

const classId = ref<string>('')

const selectedClassId = ref<string>('')
const selectedStudents = ref([])

const tableLoading = ref<boolean>(false)
const studentList = ref<ClassInfoApi.ClassStudentResp[]>([])
const getList = async () => {
  loading.value = true
  ClassInfoApi.getClassStudentList(selectedClassId.value).then((res) => {
    studentList.value = res || []
  }).finally(() => {
    loading.value = false
  })
}

const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false,
})

const columns: TableInstanceColumns[] = [
  { title: '姓名', dataIndex: 'name', slotName: 'name', width: 50 },
  { title: '性别', dataIndex: 'gender', slotName: 'gender', width: 50 },
  { title: '报名次数', dataIndex: 'enrollLessonCount', slotName: 'enrollLessonCount', width: 80 },
  { title: '剩余调课次数', dataIndex: 'remainLessonChangeCount', slotName: 'remainLessonChangeCount', width: 80 },

]

const open = async (id: string) => {
  classId.value = id
  loading.value = false
  tableLoading.value = false
  visible.value = true
}

const onSave = async () => {
  try {
    if (selectedClassId.value !== '' && selectedStudents.value.length > 0) {
      await ClassInfoApi.importClassStudents(selectedStudents.value, classId.value)
      Message.success('成功导入学生')
      emit('change')
      visible.value = false
      return true
    }
    return false
  } catch {
    return false
  }
}

const reset = () => {
  studentList.value = []
  selectedStudents.value = []
  selectedClassId.value = ''
}

defineExpose({ open })
</script>

<template>
  <ProDrawer
    v-model:visible="visible" title="导入学员"
    :loading="loading"
    @before-ok="onSave"
    @close="reset"
  >
    <ProTable v-model:selectedKeys="selectedStudents" row-key="studentId" :data="studentList" :columns="columns" :loading="tableLoading" :row-selection="rowSelection" :pagination="false">
      <template #toolbar-left>
        <ClassSelect v-model="selectedClassId" @select="getList" />
      </template>
      <template #gender="{ record }">
        <CellDict :value="record.gender" code="GenderEnum" />
      </template>
      <template #enrollLessonCount="{ record }">
        <span>{{ record.enrollment.enrollLessonCount }}</span>
      </template>
      <template #remainLessonChangeCount="{ record }">
        <span>{{ record.enrollment.remainLessonChangeCount }}</span>
      </template>
    </ProTable>
  </ProDrawer>
</template>

<style lang="less" scoped>
.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
  color: var(--color-text-1);
}
</style>
